package com.third.clock;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.third.clock.ui.CheckPermissionsActivity;
import com.third.clock.ui.fragment.MainFragment;
import com.third.clock.ui.fragment.MeFragment;
import com.third.clock.ui.fragment.MindsFragment;

public class MainActivity extends CheckPermissionsActivity implements TabLayout.OnTabSelectedListener{

    private Fragment[] fragments;

    private MainFragment mainFragment;

    private MindsFragment mindsFragment;

    private MeFragment meFragment;

    private TabLayout tabLayout;

    private int index;

    // 当前fragment的index
    private int currentTabIndex;

    private int[] tabIcons = {
            R.drawable.select_tab_main,
            R.drawable.select_tab_minds,
            R.drawable.select_tab_me
    };

    private String[] titles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        ignoreBatteryOptimization(MainActivity.this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int postion=tab.getPosition();
        onCheckedChanged(postion);
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }


    private void initView(){
        tabLayout= (TabLayout) findViewById(R.id.group_tab);

        mainFragment=new MainFragment();
        mindsFragment=new MindsFragment();
        meFragment=new MeFragment();
        fragments = new Fragment[]{mainFragment, mindsFragment, meFragment};

        MainActivity.this.getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, mainFragment).commit();

        //init 参数
        titles=new String[]{
                getResources().getString(R.string.main_tab_text),
                getResources().getString(R.string.minds_tab_text),
                getResources().getString(R.string.me_tab_text),
        };

        //配置tabLayout 图片位置
        tabLayout.addTab(tabLayout.newTab().setTag(0).setCustomView(getTabView(0)));
        tabLayout.addTab(tabLayout.newTab().setTag(1).setCustomView(getTabView(1)));
        tabLayout.addTab(tabLayout.newTab().setTag(2).setCustomView(getTabView(2)));

        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        //默认第一个选中
        tabLayout.getTabAt(0).select();


        mainFragment.initEvent();

        tabLayout.setOnTabSelectedListener(this);

    }

    public View getTabView(int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_tab_layout, null);
        TextView mTxtTitle = (TextView) view.findViewById(R.id.tablayout_text);
        mTxtTitle.setText(titles[position]);
        ImageView mImgTitle = (ImageView) view.findViewById(R.id.tablayout_icon);
        mImgTitle.setImageResource(tabIcons[position]);
        return view;
    }

    public void onCheckedChanged(int checkedId) {
        switch(checkedId){
            case 0:
                index = 0;
                mainFragment.initEvent();
                break;
            case 1:
                index = 1;
                mindsFragment.initEvent();
                break;
            case 2:
                index = 2;
                meFragment.initEvent();
                break;
        }
        if (currentTabIndex != index) {
            try {

                FragmentManager fm = getSupportFragmentManager();

                FragmentTransaction trx = getSupportFragmentManager()
                        .beginTransaction();
                getSupportFragmentManager().executePendingTransactions();//new add
                String showName = fragments[index].getClass().getSimpleName();
                Fragment sfrgment = fm.findFragmentByTag(showName);

                trx.hide(fragments[currentTabIndex]);

                if (sfrgment==null&&!fragments[index].isAdded()) {
                    trx.add(R.id.fragment_container, fragments[index],fragments[index].getClass().getSimpleName());
                }
                //trx.show(fragments[index]).commit();

                trx.show(fragments[index]).commitAllowingStateLoss();
            }catch (Exception e){

            }
        }
        currentTabIndex = index;
    }


    /**
     * 忽略电池优化
     */
    public void ignoreBatteryOptimization(Context mContext) {
        try {
            if (Build.VERSION.SDK_INT >= 23) {
                //6.0 之后版本才有
                PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
                boolean hasIgnored = powerManager.isIgnoringBatteryOptimizations(mContext.getPackageName());
                //  判断当前APP是否有加入电池优化的白名单，如果没有，弹出加入电池优化的白名单的设置对话框。
                if (!hasIgnored) {
                    Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(Uri.parse("package:" + mContext.getPackageName()));
                    startActivity(intent);
                }
            }
        }catch (Exception e){

        }
    }

    }
